package gui;

import business.UserManager;
import business.ValidationService;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@Named(value = "usernameValidatorInvitationList")
@RequestScoped
public class UsernameValidatorInvitationList implements Validator {

    @EJB
    private ValidationService validator;
    @EJB
    private UserManager userManager;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value == null) {
            throw new ValidatorException(new FacesMessage("Insert a username."));
        } else {
            String username = (String) value;
            if (username.equals(userManager.getLoggedUser().getUsername())) {
                throw new ValidatorException(new FacesMessage("You cannot invite yourself!"));
            }
            if (!validator.existUsername(username)) {
                throw new ValidatorException(new FacesMessage("This user does not exist."));
            }
        }
    }
}
